import RequestApi from '@zd/zds-request-api';
import { Toast } from '@zd/zds-wechat-lib';

import { MERCHANT_ID } from '@/constants';

const Api = new RequestApi({
  suffix: '',
  baseUrl: process.env.NODE_ENV == 'development' ? 'api' : '',
  //actions: require("./api/index").default,
  beforeSend(xhr) {
    console.log('beforesend...', xhr);
    //	console.log('404.....',xhr && xhr.readyState)
    if (process.env.NODE_ENV !== 'production') {
      //console.info(`>>>>>开发状态，当前使用的渠道是merchantId=${MERCHANT_ID}，如果数据不正常，需要确认渠道，修改constants.js下面的MERCHANT_ID<<<<<`)
      xhr.setRequestHeader('merchantId', MERCHANT_ID);
    }
  },
  start(params, options) {
    //console.log('start...',params,options)
    if (typeof options.trim == 'undefined' || options.trim) {
      let key = null,
        value = null;
      for (key in params) {
        value = params[key];
        if (typeof value === 'string') {
          params[key] = jQuery.trim(value);
        }
      }
    }
    if (
      (typeof options.loading == 'undefined' || options.loading) &&
      (typeof options.toast == 'undefined' || options.toast)
    ) {
      Toast.loading(null, 0);
    }
    if (options.method == RequestApi.method.POST) {
      options.ajaxSettings.contentType = 'application/json; charset=UTF-8';
      if (process.env.NODE_ENV !== 'production') {
        options.ajaxSettings.xhrFields = {
          withCredentials: true,
        };
      }
      return JSON.stringify(params);
    }
  },
  end(obj, options) {
    console.log('end', obj);
    if (obj && obj.SYS_HEAD && obj.SYS_HEAD.RET_CODE == '999999') {
      //console.log('onUnauthorized...1111111',obj,);
      location.replace(`/#/error`);
      //Toast.fail('请求的数据接口未找到，请检查网络...');
    }
    console.log('end...', obj, options);
    if (typeof options.loading == 'undefined' || !options.loading) {
      Toast.hide();
    }
    if (
      (typeof options.toast == 'undefined' || options.toast) &&
      obj &&
      obj.SYS_HEAD &&
      obj.SYS_HEAD.RET_STATUS != 'S'
    ) {
      //console.log("Toast.error", options, obj)
      if (obj && obj.SYS_HEAD && obj.SYS_HEAD.RET_MSG) {
        Toast.fail(obj.SYS_HEAD.RET_MSG);
      } else {
        Toast.fail('网络请求失败');
      }
    }
  },
  filter(obj) {
    return obj.SYS_HEAD.RET_STATUS == 'S';
  },

  onUnauthorized(obj) {
    console.log('onUnauthorized', obj);
    if (obj && obj.SYS_HEAD && obj.SYS_HEAD.RET_CODE == '999999') {
      //console.log('onUnauthorized...1111111',obj,);
      location.replace(`${location.origin}/#/error`);
      //Toast.fail('请求的数据接口未找到，请检查网络...');
    }
    if (obj && obj.status == 707) {
      //location.replace(`${location.origin}/chainFront/index.html`);
    }
  },
});

export default Api;
